import {reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout} from '@/api'
import {setToken, getToken, removeToken} from '@/utils/token'


const state = {
    code: '',
    token: getToken(),
    userInfo: {}
}

const actions = {
    //获取验证码
    async getCode({commit}, phone){
        let result = await reqGetCode(phone)
        if(result.code == 200){
            commit('GETCODE', result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'))
        }
    },
    //用户注册
    async userRegister({commit}, user){
        let result = await reqUserRegister(user)
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'))
        }
    },
    //用户登录[token]
    async userLogin({commit}, data){
        let result = await reqUserLogin(data)
        if(result.code == 200){
            //持久化存储token
            setToken(result.data.token)
            commit('USERLOGIN', result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'))
        }
    },

    //获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo();
        if(result.code==200){
            commit('GETUSERINFO', result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('获取用户信息失败！'))
        }
    },
    //退出登录
    async userLogout({commit}){
        let result = await reqLogout()
        if(result.code==200){
            //action里面不能操作state，需要提交mutation去修改state
            commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('退出失败！'))
        }

    },
}

const mutations = {
    GETCODE(state, code){
        state.code = code
    },
    USERLOGIN(state, token){
        state.token = token
    },
    GETUSERINFO(state, userInfo){
        state.userInfo = userInfo
    },
    CLEAR(state){
        //把仓库中相关存储清空，本地存储清空
        state.token = ''
        state.userInfo = {}
        removeToken()

    },
}

const getters = {}


export default {
    state,
    mutations,
    actions,
    getters
}